﻿using LinqModel.Models;
using Microsoft.EntityFrameworkCore;

namespace LinqModel.Data
{
    public class ApplicationDbContext: DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        { //通过依赖注入接收配置选项（如数据库连接字符串）

        }
        public DbSet<User> Users { get; set; }
        public DbSet<Order> Orders { get; set; }
        //将 C# 模型类映射到数据库表

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //配置关系
         modelBuilder.Entity<Order>()
        .HasOne(o => o.User)           // 每个 Order 属于一个 User
        .WithMany()                    // 一个 User 可以有多个 Order
        .HasForeignKey(o => o.UserId)  // 使用 UserId 作为外键
        .OnDelete(DeleteBehavior.Cascade); // 删除 User 时级联删除其所有 Order

            //配置索引
            modelBuilder.Entity<User>()
               .HasIndex(u => u.Email)
               .IsUnique();

            modelBuilder.Entity<User>()
                .HasIndex(u => u.Username)
                .IsUnique();
            // 种子数据
            modelBuilder.Entity<User>().HasData(
                new User { Id = 1, Username = "admin", Email = "admin@example.com", Age = 30 },
                new User { Id = 2, Username = "user1", Email = "user1@example.com", Age = 25 }

            );
        }
    }
}
